<template>
  <div class="app-container">
    <div class="button_warp">
      <el-button @click="toCreate">+ 创建</el-button>
    </div>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
    >
      <!-- 表单数据 -->
      <el-table-column width="60" prop="id" label="ID" max-height="50" />
      <el-table-column prop="username" label="账号名" />
      <el-table-column prop="fullname" label="昵称" />
      <el-table-column prop="email" label="邮箱地址" width="160" />
      <el-table-column prop="create_time" label="创建时间"/>
      <!-- 操作 -->
      <el-table-column label="操作" width="225">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.id == 1" size="mini" @click="toEdit(scope.row.id)">编辑</el-button>
          <el-button :disabled="scope.row.id == 1" size="mini" style="margin-left: 0px;" @click="toRole(scope.row.id)">角色</el-button>
          <el-button :disabled="scope.row.id == 1" size="mini" type="danger" style="margin-left: 0px;" @click="toDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="titleName" :visible.sync="addFormVisible">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="帐号名：" prop="username">
          <el-input v-if="addForm.add === true" v-model="addForm.username" auto-complete="off"/>
          <span v-else>{{ addForm.username }}</span>
        </el-form-item>
        <el-form-item label="邮箱地址：" prop = "email">
          <el-input v-model="addForm.email" auto-complete="off" />
        </el-form-item>
        <el-form-item v-if="addForm.add === true" label="密码：" prop="pwd">
          <div><el-input v-model="addForm.pwd" type="password" style="width: 500px;" auto-complete="off" /><br>
            (长度在 6 到 8 个字符)
          </div>
        </el-form-item>
        <el-form-item v-if="addForm.add === true" label="确认密码：" prop="repwd">
          <div><el-input v-model="addForm.repwd" type="password" style="width: 500px;" auto-complete="off"/><br>
            (长度在 6 到 8 个字符)
          </div>
        </el-form-item>
        <el-form-item label="昵称：" prop="fullname">
          <el-input v-model="addForm.fullname" auto-complete="off"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="rolesVisible">
      <el-form>
        <el-form-item>
          <el-checkbox-group v-model="checkList">
            <el-checkbox v-for="item in roleData" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="rolesVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <div class="block myPaginate">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        :total="dataTotal"
        layout="total, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getAdminUser, createUser, editUser, userDetail, userDelete, getRoles } from '../../../api/admin'
export default {
  data() {
    return {
      tableData: [],
      roleData: [],
      addForm: {
        add: true,
        username: '',
        email: '',
        pwd: '',
        repwd: '',
        fullname: ''
      },
      admin_id: 0,
      checkList: [],
      titleName: '新增',
      addFormRules: {
        username: [
          { required: true, message: '请输入帐号名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        pwd: [
          { required: true, min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' }
        ],
        repwd: [
          { required: true, min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' }
        ],
        fullname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ]
      },
      addFormVisible: false,
      rolesVisible: false,
      currentPage: 1, // 当前页
      dataTotal: 0, // 数据总数
      pageSize: 20,
      loading: true
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      const params = {
        page: this.currentPage,
        limit: this.pageSize
      }
      getAdminUser(params).then(data => {
        console.log(data)
        this.loading = false
        if (data.code === 0) {
          this.tableData = data.data.list
          this.dataTotal = data.data.count
        } else {
          this.$message({
            showClose: true,
            message: data.msg,
            type: 'error'
          })
        }
      })
    },
    // 新增
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.addForm.add) {
            this.addForm.role_id = this.role_id
            const para = Object.assign({}, this.addForm)
            createUser(para).then(data => {
              if (data.code === 0) {
                this.$message({
                  message: '创建成功',
                  type: 'success'
                })
                this.$refs['addForm'].resetFields()
                this.addFormVisible = false
                this.getData()
              } else {
                this.$message({
                  showClose: true,
                  message: data.msg,
                  type: 'error'
                })
              }
            })
          } else {
            const para = Object.assign({}, this.addForm)
            editUser(para).then(data => {
              // this.addLoading = false;
              if (data.code === 0) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.$refs['addForm'].resetFields()
                this.addFormVisible = false
                this.getData()
              }
            })
          }
        }
      })
    },
    roleSubmit() {
      console.log(this.checkList)
    },
    toCreate() {
      this.addFormVisible = true
      this.addForm.add = true
      this.titleName = '新增'
    },
    toEdit(id) {
      userDetail({ id: id }).then(data => {
        if (data.code === 0) {
          const userData = data.data
          this.addForm.id = userData.id
          this.addForm.username = userData.username
          this.addForm.pwd = userData.pwd
          this.addForm.email = userData.email
          this.addForm.fullname = userData.fullname
        }
      })
      this.titleName = '编辑'
      this.addFormVisible = true
      this.addForm.add = false
    },
    toRole(id) {
      this.admin_id = id
      this.rolesVisible = true
      getRoles().then(data => {
        console.log(data)
        this.roleData = data.data
      })
    },
    toDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userDelete({ id: id }).then(data => {
          if (data.code === 0) {
            this.getData()
            this.$message({
              showClose: true,
              message: data.data,
              type: 'success'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分页事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getData()
    }
  }
}
</script>
